package com.ray.life;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.google.android.maps.GeoPoint;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends ListActivity {
    private final String TAG = "MainActivity";

    private final int MENU_SELECT_CITY = 0;
    private final int MENU_SHOW_ON_MAP = 1;
    private final int MENU_NEARBY = 2;

    private final int MENU_OFFSET = 10;

    private final int MSG_SHOW_ALL = 0;
    private final int MSG_SHOW_NEARBY = 1;
    /** 9 is Kaohsiung, default city*/
    private int mCityIndex = 9;

    private TextView mTitle;
    private ProgressDialog mProgressDialog;

    private static ArrayList<News> mList = new ArrayList<News>();
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(final Message msg) {
            mProgressDialog.dismiss();

            switch (msg.arg1) {
                case MSG_SHOW_ALL:
                    setListAdapter(new NewsAdapter(MainActivity.this, mList, false));
                    break;
                case MSG_SHOW_NEARBY:
                    setListAdapter(new NewsAdapter(MainActivity.this, mList, true));
                    break;
            }
        }
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);

        StartActivity.show(MainActivity.this, 0);
        /* set text in title bar */
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);

        mTitle = (TextView) findViewById(R.id.title_text);
        mCityIndex = getCityIndex();
        String title = this.getResources().getString(R.string.app_name).concat(" - ").concat(Constants.COUNTY_NAME[mCityIndex]);
        mTitle.setText(title);

        getRssData(Constants.COUNTY_RSS_URLS[mCityIndex]);
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        News news = (News) mList.get(position);

        Intent intent = new Intent();
        intent.setClass(MainActivity.this, NewsDetailActivity.class);

        Bundle bundle = new Bundle();
        bundle.putString(Constants.KEY_TITLE, news.getTitle());
        bundle.putString(Constants.KEY_DESC, news.getDesc());
        bundle.putString(Constants.KEY_LINK, news.getLink());
        bundle.putInt(Constants.KEY_INDEX, position);

        intent.putExtras(bundle);
        startActivity(intent);
    }

    private void getRssData(final String path) {
        mProgressDialog = ProgressDialog.show(this, "Processing . . .", "Getting data", true, false);
        Log.i(TAG, "rss url is " + path);

        /** fork a thread to access rss data */
        new Thread() {
            @Override
            public void run() {
                ArrayList<News> data = new ArrayList<News>();
                URL url = null;

                try {
                    url = new URL(path);

                    SAXParserFactory spf = SAXParserFactory.newInstance();
                    SAXParser sp = spf.newSAXParser();
                    XMLReader xr = sp.getXMLReader();

                    RSSHandler rssHandler = new RSSHandler();
                    xr.setContentHandler(rssHandler);
                    xr.parse(new InputSource(url.openStream()));
                    data = rssHandler.getParsedData();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                mList = data;

                Message msg = new Message();
                msg.arg1 = MSG_SHOW_ALL;
                mHandler.sendMessage(msg);
            }
        }.start();
    }

    private int getCityIndex() {
        int cityIndex = 9;// 9 is Kaohsiung
        Location location = LocationHelper.getLocation((LocationManager) getSystemService(Context.LOCATION_SERVICE));
        GeoPoint gp = LocationHelper.getGeoPoint(location);
        Geocoder geocoder = new Geocoder(MainActivity.this);
        String result = null;

        try {
            List<Address> addresses = geocoder.getFromLocation(gp.getLatitudeE6() / LocationHelper.MILLION, gp.getLongitudeE6() / LocationHelper.MILLION, 1);

            if (addresses != null) {
                result = addresses.get(0).getAdminArea();
                Log.i(TAG, "current city is " + result);
            }

            for (int i = 0; i < Constants.COUNTY_NAME_ENG.length; i++) {
                if (result.indexOf(Constants.COUNTY_NAME_ENG[i]) > 0) {
                    cityIndex = i;
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return cityIndex;
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        SubMenu sm = menu.addSubMenu(0, MENU_SELECT_CITY, 0, R.string.select_city);
        for (int i = 0; i < Constants.COUNTY_NAME.length; i++) {
            sm.add(0, i + MENU_OFFSET, i, Constants.COUNTY_NAME[i]);
        }
        menu.add(0, MENU_SHOW_ON_MAP, 1, R.string.show_on_map);
        menu.add(0, MENU_NEARBY, 2, R.string.show_nearby);

        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case 0:
                return true;
            case 1:
                MapViewActivity.show(MainActivity.this, mCityIndex);

                return true;
            case 2:
                Message msg = new Message();
                msg.arg1 = MSG_SHOW_NEARBY;
                mHandler.sendMessage(msg);

                return true;    
            default:
                // TODO wrong code?? add restrictions, if item id > menu + submenu, return false
                mCityIndex = item.getItemId() - MENU_OFFSET;
                mTitle = (TextView) findViewById(R.id.title_text);
                String cityName = Constants.COUNTY_NAME[mCityIndex];
                String title = this.getResources().getString(R.string.app_name).concat(" - ").concat(cityName);
                mTitle.setText(title);

                Log.i(TAG, "select city : " + cityName);
                getRssData(Constants.COUNTY_RSS_URLS[mCityIndex]);

                return true;
        }
    }

    public static ArrayList<News> getNewsList() {
        return mList;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }

        super.onActivityResult(requestCode, resultCode, data);
    }
}